<?php

namespace App\Http\Controllers\Admin\v1;

use App\Helpers\Tree;
use App\Http\Requests\SysDepartmentsRequest;
use App\Models\Sys\SysDepartments;
use Illuminate\Http\Request;
use Jiannei\Response\Laravel\Support\Facades\Response;

/**
 * 部门管理
 * SysDepartmentsController class
 */
class SysDepartmentsController extends BaseController
{
    public function __construct()
    {
        $this->modelClass = new SysDepartments();
        $this->requestClass = SysDepartmentsRequest::class;
        $this->title = '数据字典';
        $this->initialize();
    }

    /**
     * 列表
     * index function
     *
     * @desc Display a listing of the resource.
     * @desc index： GET /re
     *
     * @param paging 是否分页，默认true
     * @param limit 显示条数
     * @param page 当前页
     * @param sort 排序参数
     * @param sortOrder 排序方式
     * @return void
     */
    public function index(Request $request)
    {
        $requestData = $request->all();
        [$sort, $sortOrder] = [
            isset($requestData['sort']) ? $requestData['sort'] : 'sort',
            isset($requestData['sortOrder']) ? $requestData['sortOrder'] : 'desc',
        ];
        $models = $this->modelClass::query();

        if (isset($requestData['parent_id'])) {
            $models->where('parent_id', $requestData['parent_id']);
        }
        if (isset($requestData['label'])) {
            $models->where('label', 'like', '%'.$requestData['label'].'%');
        }
        if (isset($requestData['status'])) {
            $models->where('status', $requestData['status']);
        }

        $data = $models->orderBy($sort, $sortOrder)->get();

        Tree::init($data, 'parent_id', 'id', 'name');
        $tree = Tree::get_childall_data();

        return Response::success($tree);
    }
}
